using System;
using System.Net.Sockets;

namespace TXK
{
	public class S7ScoketBase
	{
		public Socket tcpclient;

		public Guid Token { get; set; }

		public XktResult<byte[]> ReceiveByMessage(Socket socket, int timeOut, INetMessage netMessage, Action<long, long> reportProgress = null)
		{
			if (netMessage == null)
			{
				return this.Receive(socket, -1, timeOut);
			}
			XktResult<byte[]> xktResult;
			xktResult = this.Receive(socket, netMessage.ProtocolHeadBytesLength, timeOut);
			if (!xktResult.IsSuccess)
			{
				return xktResult;
			}
			netMessage.HeadBytes = xktResult.Content;
			int contentLengthByHeadBytes;
			contentLengthByHeadBytes = netMessage.GetContentLengthByHeadBytes();
			if (contentLengthByHeadBytes <= 0)
			{
				return xktResult;
			}
			XktResult<byte[]> xktResult2;
			xktResult2 = this.Receive(socket, contentLengthByHeadBytes, timeOut, reportProgress);
			if (!xktResult2.IsSuccess)
			{
				return xktResult2;
			}
			netMessage.ContentBytes = xktResult2.Content;
			return XktResult.CreateSuccessResult(ByteArrayLib.CombineTwoByteArray(xktResult.Content, xktResult2.Content));
		}

		private XktResult<byte[]> Receive(Socket socket, int length, int timeOut = 60000, Action<long, long> reportProgress = null)
		{
			if (length == 0)
			{
				return XktResult.CreateSuccessResult(new byte[0]);
			}
			try
			{
				socket.ReceiveTimeout = timeOut;
				if (length > 0)
				{
					return XktResult.CreateSuccessResult(this.ReadBytesFromSocket(socket, length, reportProgress));
				}
				byte[] array;
				array = new byte[1024];
				return XktResult.CreateSuccessResult(ByteArrayLib.GetByteArray(array, 0, socket.Receive(array)));
			}
			catch (Exception ex)
			{
				return new XktResult<byte[]>(0, ex.Message);
			}
		}

		private byte[] ReadBytesFromSocket(Socket socket, int receive, Action<long, long> reportProgress = null)
		{
			byte[] array;
			array = new byte[receive];
			int num;
			num = 0;
			while (num < receive)
			{
				int num2;
				num2 = socket.Receive(array, num, Math.Min(receive - num, 8192), SocketFlags.None);
				num += num2;
				if (num2 == 0)
				{
					throw new Exception();
				}
				reportProgress?.Invoke(num, receive);
			}
			return array;
		}
	}
}
